#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import sys,re,urllib2,urllib,time,xlwt,os,json,codecs,csv,smtplib

type = sys.getfilesystemencoding() 
reload(sys)  
sys.setdefaultencoding('utf8')


class Youtube_video:
    #开始方法
    def __init__(self):
        self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        self.headers    = { 'User-Agent' : self.user_agent }
        self.channels = []
        self.channel_video = []
        self.channel_viewCount = ''

    def start(self,channel_id):
        self.channel_id = channel_id
        # UC02UVoPQeVi5yVJAMmn1Fmw,UC-MByr5LRnWmVN94Ija4XJg
        # 获取 go车志 频道数据
        self.getChannelData(channel_id)
        
        # 获取频道影片列表 items 数据
        self.getChannelItems(channel_id)

        # # 获取影片数据
        self.getVideoData()

    def getChannelData(self,channel_array):
        url             = 'https://www.googleapis.com/youtube/v3/channels'
        part            = 'snippet,contentDetails,statistics'
        key             = 'AIzaSyBS8p-aiWmI6jeCFvRZTYKgO5AkqrAXmkA'
        channel_url     = url + '?id='+ channel_array +'&part='+ part +'&key='+ key
        request         = urllib2.Request(channel_url, headers = self.headers)
        response        = urllib2.urlopen(request).read()
        channel_msg     = json.loads(response)

        self.channel_viewCount =  channel_msg['items'][0]['statistics']['subscriberCount']
        self.channels = channel_msg
        

    def getChannelItems(self,channel_array):
        url             = 'https://www.googleapis.com/youtube/v3/search'
        part            = 'snippet,id'
        key             = 'AIzaSyBS8p-aiWmI6jeCFvRZTYKgO5AkqrAXmkA'
        channel_url     = url +'?channelId='+ channel_array +'&part='+ part +'&key='+ key +'&order=date&maxResults=20'
        request         = urllib2.Request(channel_url, headers = self.headers)
        response        = urllib2.urlopen(request).read()
        channel_msg     = json.loads(response)
        
        self.channel_video = channel_msg


    def getVideoData(self):
        vide_id = ''
        for item in self.channel_video['items']:
            str_date = item['snippet']['publishedAt']
            try:  
                if(self.comparison(str_date[0:10])):
                    vide_id += item['id']['videoId'] + ','
            except:
                print u'未找到 videoId'

        
        # 获取用户数据
        url         = 'https://www.googleapis.com/youtube/v3/videos'
        video_array = vide_id
        part        = 'snippet,contentDetails,statistics'
        key         = 'AIzaSyBS8p-aiWmI6jeCFvRZTYKgO5AkqrAXmkA'
        video_url   = url + '?id='+video_array+'&part='+part+'&key='+ key
        request     = urllib2.Request(video_url, headers = self.headers)
        response    = urllib2.urlopen(request).read()
        msg         = json.loads(response)

        self.createCsv(msg)

    def comparison(self,str_date):
        st = time.strptime(str_date, '%Y-%m-%d')
        month_day = time.time()
        # 计算剩余天数
        day = int((month_day - time.mktime(st))/(60*60*24))
        judge = True if day<45 else False
       
        return judge

    def createCsv(self,items):
        on_off = True
        if (items):
            month_day = time.strftime("%m-%d")
            # 写入数据
            if os.path.exists('./video-%s.csv'%(month_day)) == False:
                with codecs.open('./video-%s.csv'%(month_day), 'w', 'utf_8_sig') as f:
                    f.write('标题,项目,%s\n'%(month_day))
                    f.write('GO车志,订阅数,%s'%(self.channel_viewCount))

            for item in items['items']:
                with codecs.open('./video-%s.csv'%(month_day), 'a', 'utf_8') as f:
                    if( self.channel_id == 'UC02UVoPQeVi5yVJAMmn1Fmw' and on_off ):
                        f.write('\r\n\n\n全名疯车Bar,订阅数,%s'%(self.channel_viewCount))
                        on_off = False
                    if( self.channel_id == 'UCnao4xB4LPLa6oFLjbOg0oQ' and on_off ):
                        f.write('\r\n\n\狂人日誌,订阅数,%s'%(self.channel_viewCount))
                        on_off = False
                    if( self.channel_id == 'UCKEshOzNkXEAtt6h1zS0A6Q' and on_off ):
                        f.write('\r\n\n\Tcar試車頻道,订阅数,%s'%(self.channel_viewCount))
                        on_off = False
                    if( self.channel_id == 'UCD76jE_-uOSeyC2q8jX7pVQ' and on_off ):
                        f.write('\r\n\n\carplay,订阅数,%s'%(self.channel_viewCount))
                        on_off = False
                    if( self.channel_id == 'UCW92-RPH4xq1YqVbON4D0fg' and on_off ):
                        f.write('\r\n\n\ucar,订阅数,%s'%(self.channel_viewCount))
                        on_off = False

                    f.write('\r\n\n,发布时间,%s\n,观看次数,%s,\n%s,留言数,%s\n,表态,%s\n'%((item['snippet']['publishedAt'])[0:10],item['statistics']['viewCount'],item['snippet']['title'],item['statistics']['commentCount'],(int(item['statistics']['likeCount'])+int(item['statistics']['dislikeCount']))))
            if( self.channel_id == 'UCW92-RPH4xq1YqVbON4D0fg' ):
                # self.sendEmail()
        else:
            exit(u'未找到数据')
            
    # def sendEmail(self):
    #     sender = 'ljp@addcn.com'
    #     passwd = 'Fj0491062'
    #     receivers = ['wnm@addcn.com','chendachao@addcn.com','ljp@addcn.com']
    #     month_day = time.strftime("%m-%d")
         
    #     emails = [elem.strip().split(',') for elem in receivers]
    #     msg = MIMEMultipart()
    #     msg['Subject'] = 'YouTube-%s.csv'%(month_day)
    #     msg['From'] = sender
    #     msg['To'] = ','.join(receivers)
         
    #     msg.preamble = 'Multipart massage.\n'
    #     part = MIMEText("YouTube")
    #     msg.attach(part)

    #     part = MIMEApplication(open('./video-%s.csv'%(month_day),"rb").read())

    #     part.add_header('Content-Disposition', 'attachment', filename='./video-%s.csv'%(month_day))
    #     msg.attach(part)
         
    #     smtp = smtplib.SMTP("smtp.gmail.com:587")
    #     smtp.ehlo()
    #     smtp.starttls()
    #     smtp.login(sender, passwd)
         
    #     smtp.sendmail(msg['From'], emails , msg.as_string())
    #     print 'Send mails to',msg['To']

spider = Youtube_video()

channel_id_array = [
    'UC-MByr5LRnWmVN94Ija4XJg', 
    'UC02UVoPQeVi5yVJAMmn1Fmw',
    'UCnao4xB4LPLa6oFLjbOg0oQ',
    'UCKEshOzNkXEAtt6h1zS0A6Q',
    'UCD76jE_-uOSeyC2q8jX7pVQ',
    'UCW92-RPH4xq1YqVbON4D0fg'
]
for i in channel_id_array:
    spider.start(i)

